package com.smartinput.device.application.service

import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean

/**
 * 设备状态管理器
 * 负责协调WebSocket连接状态和数据库状态，避免循环依赖
 */
@Component
class DeviceStatusManager {
    
    private val logger = LoggerFactory.getLogger(DeviceStatusManager::class.java)
    
    // 实时WebSocket连接状态缓存
    private val webSocketStatusCache = ConcurrentHashMap<String, AtomicBoolean>()
    
    /**
     * 更新WebSocket连接状态
     */
    fun updateWebSocketStatus(deviceId: String, isOnline: Boolean) {
        webSocketStatusCache[deviceId] = AtomicBoolean(isOnline)
        logger.debug("更新WebSocket状态: deviceId=$deviceId, online=$isOnline")
    }
    
    /**
     * 移除设备状态缓存
     */
    fun removeDeviceStatus(deviceId: String) {
        webSocketStatusCache.remove(deviceId)
        logger.debug("移除设备状态缓存: deviceId=$deviceId")
    }
    
    /**
     * 获取设备实时状态
     */
    fun isDeviceOnline(deviceId: String): Boolean {
        return webSocketStatusCache[deviceId]?.get() ?: false
    }
    
    /**
     * 获取所有在线设备ID
     */
    fun getOnlineDeviceIds(): Set<String> {
        return webSocketStatusCache.entries
            .filter { it.value.get() }
            .map { it.key }
            .toSet()
    }
    
    /**
     * 检查状态是否一致
     */
    fun isStatusConsistent(deviceId: String, databaseOnline: Boolean): Boolean {
        val webSocketOnline = isDeviceOnline(deviceId)
        return webSocketOnline == databaseOnline
    }
    
    /**
     * 获取状态不一致的设备
     */
    fun getInconsistentDevices(deviceIds: List<String>, databaseStatusMap: Map<String, Boolean>): Map<String, Boolean> {
        return deviceIds.associateWith { deviceId ->
            val webSocketOnline = isDeviceOnline(deviceId)
            val databaseOnline = databaseStatusMap[deviceId] ?: false
            webSocketOnline
        }.filter { (deviceId, webSocketOnline) ->
            val databaseOnline = databaseStatusMap[deviceId] ?: false
            webSocketOnline != databaseOnline
        }
    }
} 